package code.classic150on2025;

import utils.TreeNode;

import java.util.*;

public class BinTreeLevel {
    // 199. 二叉树的右视图
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null)
            return list;
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int count = queue.size();
            for (int i = 0; i < count; i++) {
                TreeNode now = queue.poll();
                if (i == 0)
                    list.add(now.val);
                if (now.right != null)
                    queue.offer(now.right);
                if (now.left != null)
                    queue.offer(now.left);
            }
        }
        return list;
    }

    // 102. 二叉树的层序遍历
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if (root == null)
            return list;
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int count = queue.size();
            List<Integer> l = new ArrayList<>();
            for (int i = 0; i < count; i++) {
                TreeNode now = queue.poll();
                l.add(now.val);
                if (now.left != null)
                    queue.offer(now.left);
                if (now.right != null)
                    queue.offer(now.right);
            }
            list.add(l);
        }
        return list;
    }

    // 103. 二叉树的锯齿形层序遍历
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> lists = new ArrayList<>();
        if (root == null)
            return lists;
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        boolean flag = true;
        while (!queue.isEmpty()) {
            int count = queue.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < count; i++) {
                TreeNode now = flag ? queue.pollLast() : queue.pollFirst();
                list.add(now.val);
                if (flag) {
                    if (now.left != null)
                        queue.addFirst(now.left);
                    if (now.right != null)
                        queue.addFirst(now.right);
                } else {
                    if (now.right != null)
                        queue.addLast(now.right);
                    if (now.left != null)
                        queue.addLast(now.left);
                }
            }
            lists.add(list);
            flag = !flag;
        }
        return lists;
    }
}
